<template>
  <el-dialog
          v-model="dialogShow"
          :close-on-click-modal="false"
          custom-class="mydialog"
          width="40%"
          :title="title"
          :before-close="close"
  >
    <el-form
            ref="formRef"
            :model="formData"
            :label-width="formLabelWidth"
            size="small"
            :rules="rules"
    >
      <el-form-item
              label="区域名称"
              prop="salesAreaName"
      >
        <el-input
                v-model="formData.salesAreaName"
                clearable
                placeholder="请输入区域名称"
                autocomplete="off"
        />
      </el-form-item>
      <el-form-item
              label="上级区域"
              prop="parentId"
      >
        <el-cascader
                ref="refHandle"
                v-model="formData.parentId"
                :popper-append-to-body="false"
                :options="listData"
                placeholder="请选择上级区域"
                style="width: 100%"
                :show-all-levels="false"
                :props="{expandTrigger: 'hover', checkStrictly: true ,label:'salesAreaName',value:'id'}"
                @change="onChange"
        />
      </el-form-item>
      <el-form-item
              label="行政区域"
              prop="area"
      >
        <el-cascader
                ref="cascader"
                v-model="formData.area"
                :popper-append-to-body="false"
                style="width: 100%"
                :props="props1"
                :options="citys"
                placeholder="请选择行政区域"
                collapse-tags
                clearable
                @change="areaChange"
        />
      </el-form-item>

      <el-form-item
              label="负责职员"
              prop="userIds"
      >
        <el-select
                v-model="formData.userIds"
                style="width: 100%"
                multiple
                placeholder="请选择负责职员"
        >
          <el-option
                  v-for="item in headOptions"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
                class="border-btn"
                size="small"
                @click="close"
        >取消</el-button>
        <el-button
                class="main-btn"
                size="small"
                type="primary"
                @click="confirm"
        >保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
  import {getScreenAreaData} from '../../../../../../utils/areaFuc'
  import area from '@/utils/area.js'
  import {defineComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs,} from 'vue'

  export default defineComponent({
    name: 'CreateOrChange',
    emits:['success'],
    props: {
      title: {
        type: String,
        default: '',
      },
      // form: {
      //   type: Object,
      //   default: () => {},
      // },
    },
    setup(props, context) {

      const api = inject('api')
      const currentInstance = getCurrentInstance()
      var formLabelWidth = ref(120)
      var cascader = ref(null)
      var formRef = ref(null)
      var citys = ref(area)
      const props1 = reactive({
        multiple: true,
        expandTrigger: 'hover',
        label: 'regionName',
        value: 'regionCode',
      })
      var dialogShow = ref(false)
      const prop = ref({
        label: 'salesAreaName',
        value: 'id',
        children: 'children',
        emitPath: false,
        checkStrictly: true,
      })

      const open = (val) => {
        dialogShow.value = true
        if (val) {
          data.formData.id = val.id
          data.formData.salesAreaName = val.salesAreaName
          data.formData.parentId = val.parentId
          data.formData.regionList = val.regionList
          data.formData.region = val.region
          data.formData.area = val.area
          data.formData.userIds = val.userIds
        } else {
          setTimeout(() => {
            if (formRef.value){
              formRef.value.clearValidate()
            }
          })
        }
        getArea()
        getList()

        setTimeout(()=>{
          checkArea()
        })

      }

      const checkArea = () => {
        if (data.formData.region.length) {
          data.formData.area = []
          data.formData.area = currentInstance.proxy.getCascaderAreaData(
                  data.formData.region
          )
        }
      }
      const parentAreas = ref([])
      var headOptions = ref([])
      var data = reactive({
        formData: {
          id: '',
          salesAreaName: '',
          parentId: 0,
          area: [],
          regionList: [],
          region: [],
          userIds: [],
        },
      })
      var form = reactive({
        id: '',
        salesAreaName: '',
        parentId: 0,
        area: [],
        regionList: [],
        region: [],
        userIds: [],
      })
      var rules = reactive({
        salesAreaName: [
          { required: true, message: '请输入区域名称', trigger: 'blur' },
        ],
        // parentId: [
        //    { required: false, message: '请选择上级区域', trigger: 'change' },
        //  ],
        area: [{ required: true, message: '请选择行政区域', trigger: 'change' }],
        userIds: [
          { required: true, message: '请选择负责职员', trigger: 'change' },
        ],
      })
      const onChange = (val) => {
        if (val) {
          data.formData.parentId = val[val.length - 1]
        } else {
          data.formData.parentId = 0
        }

        getArea()
        data.formData.regionList = []
        data.formData.region = []
        data.formData.area = []
      }

      const getArea = () => {
        const data1 = {
          parentId: 0,
        }
        if (data.formData.parentId) {
          data1.parentId = data.formData.parentId
        }
        if (data.formData.id) {
          data1.id = data.formData.id
        }
        api.system.SELLAREA_SELECT_AREA(data1).then((res) => {
          if (!res.code) {
            citys.value = res.data
          } else {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: res.msg,
            })
          }
        })
      }

      const areaChange = (val) => {
        console.log(val)

        const serve = currentInstance.proxy.getServeAreaData(
                val,
                cascader.value.getCheckedNodes()
        )
        console.log(serve)
        data.formData.region = serve
        data.formData.regionList = getScreenAreaData(serve)
        // console.log("转换服务器地址 ",serve)
        // console.log("转换本地地址 ",currentInstance.proxy.getCascaderAreaData(serve))
      }
      const close = () => {
        (data.formData.salesAreaName = ''), (data.formData.regionList = [])
        data.formData.region = []
        ;(data.formData.area = []), (data.formData.parentId = 0)
        data.formData.userIds = []
        formRef.value.resetFields()
        setTimeout(() => {
          dialogShow.value = false
          formRef.value.clearValidate()
        })

        //   formRef.value.resetFields()
        //   formRef.value.clearValidate('area')
      }
      const confirm = () => {
        console.log(props.title)
        if (props.title == '添加营销区域') {
          formRef.value.validate((valid) => {
            if (valid) {
              const data1 = {
                salesAreaName: data.formData.salesAreaName,
                regionList: data.formData.regionList,
                region: data.formData.region,
                parentId: data.formData.parentId,
                userIds: data.formData.userIds,
              }
              api.system.SELLAREA_CREATE(data1).then((res) => {
                if (!res.code) {
                  currentInstance.proxy.customMessage({
                    type: 'success',
                    message: '添加成功',
                  })
                  context.emit('success')
                  close()
                } else {
                  currentInstance.proxy.customMessage({
                    type: 'error',
                    message: res.msg,
                  })
                }
              })
              // close()
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          formRef.value.validate((valid) => {
            if (valid) {
              const data1 = {
                id: data.formData.id,
                salesAreaName: data.formData.salesAreaName,
                regionList: data.formData.regionList,
                region: data.formData.region,
                parentId: data.formData.parentId,
                userIds: data.formData.userIds,
              }
              api.system.SELLAREA_UPDATE(data1).then((res) => {
                if (!res.code) {
                  currentInstance.proxy.customMessage({
                    type: 'success',
                    message: '编辑成功',
                  })
                  context.emit('success')
                  close()
                } else {
                  currentInstance.proxy.customMessage({
                    type: 'error',
                    message: res.msg,
                  })
                }
              })
            } else {
              console.log('error submit!!')
              return false
            }
          })
        }
      }
      var listData = ref([])
      const getList = () => {
        api.system.SELLAREA_LIST().then((res) => {
          console.log(res)
          if (res.code == 0) {
            listData.value = res.data
            console.log(listData)
          }
        })
      }

      // 获取负责人
      const handlHead = () => {
        api.terminal.HEAD_PEOPLE(1).then((res) => {
          if (res.code === 0) {
            headOptions.value = res.data
          }
        })
      }

      onMounted(() => {
        handlHead()
      })
      return {
        ...toRefs(data),
        dialogShow,
        prop,
        open,
        form,
        rules,
        parentAreas,
        citys,
        props1,
        areaChange,
        close,
        currentInstance,
        formRef,
        api,
        cascader,
        confirm,
        getList,
        listData,
        formLabelWidth,
        onChange,
        headOptions,
      }
    },
  })
</script>
